package org.jackysoft.service.impl;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.bean.define.TransactionNames;
import org.jackysoft.data.AbstractDataProvider;
import org.jackysoft.entity.Department;
import org.jackysoft.entity.Role;
import org.jackysoft.entity.SecurityRole;
import org.jackysoft.entity.User;
import org.jackysoft.entity.nosql.NameValuePair;
import org.jackysoft.entity.nosql.SecurityRoleNotify;
import org.jackysoft.entity.nosql.UserInfo;
import org.jackysoft.mapper.DepartmentMapper;
import org.jackysoft.mapper.RoleMapper;
import org.jackysoft.mapper.SecurityRoleMapper;
import org.jackysoft.mapper.UserMapper;
import org.jackysoft.service.DepartmentService;
import org.jackysoft.service.UserService;
import org.jackysoft.util.OperationType;
import org.jackysoft.util.Page;
import org.jackysoft.util.VariableType;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

@Service("userDetailsService")
public class UserServiceImpl extends AbstractDataProvider<User>
		implements UserService {

	protected static final Log log = LogFactory.getLog(UserServiceImpl.class);
	@Resource
	UserMapper mapper;
	@Resource
	DepartmentService deptService;
	@Resource
	DepartmentMapper deptMapper;
	@Resource
	RoleMapper roleMapper;
	@Resource
	SecurityRoleMapper secuMapper;
	public UserServiceImpl() {
		super();
	}
	
	@Override
	@Transactional(value = TransactionNames.IDT_TRANSACTION, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.SERIALIZABLE)
	public void remove(User user) throws DataAccessException {
		mapper.setEnabled(0, user.getUsername());
	}

	@Override
	public Collection<User> searchs(String search)  {
		
		Collection<User> results = mapper.searchUsers(search);
		return results;
	}

	
	@Override
	public void saveProfile(User user) throws DataAccessException {

		mapper.update(user);

	}

	@Override
	public Page findByDepartment(String dept, int page, int rows)
			throws DataAccessException {
		
		Collection<User> list = mapper.findOfType("department_id", dept, page*rows, rows);
		int count = mapper.countOf("department_id", dept);
		
		Page pager = Page.build(page, count, list);
				
		return pager;
	}

	@Override
	public Page findByRole(String role, int page, int rows) throws DataAccessException {
		Collection<User> list = mapper.findOfType("role_id", role, page*rows, rows);
		int count = mapper.countOf("role_id", role);
		
		Page pager = Page.build(page, count, list);
				
		return pager;
	}
	
	
	@Override
	public Page findBySecurityRole(final String role, int page, int rows)
			throws DataAccessException {
		
		Collection<User> list = mapper.findBySecurityRole(role, page*rows, rows);
		int count = mapper.countOfSecurityRole(role);
		Page pager = Page.build(page, count, list);
		return pager;
	}
	
	

	@Override
	public Collection<User> findAllByDepartments(Collection<Department> depts)
			throws DataAccessException {
		List<String> ids = Lists.newArrayList();
		for(Department d:depts) ids.add(d.getId());
		String idz = Joiner.on("','").join(ids);
		
		Collection<User> users = mapper.findAllByDepartment(idz);
		return users;
	}

	
	@Override
	public void reset(String dept) throws DataAccessException {
		mapper.resetDepartment(dept);
	}
	
	@Override
	public User find(String name) {
		User fuser = mapper.findOne(name);
	    Department dept  = deptMapper.findByUser(name);
	    fuser.setDepartment(dept);
		Role role = roleMapper.findByUser(name);
		fuser.setRole(role);				
		Collection<SecurityRole> secus = secuMapper.findByUser(name);
		fuser.setAuthoritys(secus);
		return fuser;
	}


	@Override
	@Transactional(value = TransactionNames.IDT_IBATIS_TRANSACTION, readOnly = true)
	public User getLoginInfo(String name) throws DataAccessException {
		User fuser = mapper.findOne(name);
	    Department dept  = deptService.findByUser(name);
	    fuser.setDepartment(dept);
		Role role = roleMapper.findByUser(name);
		fuser.setRole(role);				
		Collection<SecurityRole> secus = secuMapper.findByUser(name);
		fuser.setAuthoritys(secus);
		return fuser;
	}

	@Override
	public void pass(Collection<String> beans) throws DataAccessException {
	       for(String name:beans){
	    	   if(name==null)continue;
	    	   mapper.setEnabled(1, name);
	       }
	}

	@Override
	public boolean exists(String username) throws DataAccessException {
		return mapper.findOne(username) != null;
	}

	@Override
	public void save(User b) throws DataAccessException {
		SecurityRoleNotify notify = new SecurityRoleNotify(b.getUsername()
				+ "[" + b.getLocalName() + "需要审核]", new Date(),
				OperationType.Create);
		notifyService.save(notify);
		b.setEnabled(true);
		mapper.inert(b);
	}

	@Override
	public void update(User b) throws DataAccessException {
		SecurityRoleNotify notify = new SecurityRoleNotify(b.getUsername()
				+ "[" + b.getLocalName() + "需要审核]", new Date(),
				OperationType.Update);
		notifyService.save(notify);
		b.setEnabled(true);
		mapper.update(b);
	}

	@Override
	public void marked4Remove(User owner) throws DataAccessException {
		mapper.setEnabled(0, owner.getUsername());

	}


	@Override
	public UserInfo getUserInfo(String name) throws DataAccessException {
		User user = find(name);
		UserInfo ui = new UserInfo();
		ui.setName(name);
		ui.setLocalName(user.getLocalName());
		ui.setGroup(new NameValuePair(user.getDepartment().getId(), user
				.getDepartment().getName()));
		ui.setRole(new NameValuePair(user.getRole().getId(), user.getRole()
				.getName()));
		List<NameValuePair> auths = Lists.newArrayList();
		for (SecurityRole ar : user.getAuthoritys()) {
			auths.add(new NameValuePair(ar.getName(), ar.getDescription()));
		}
		ui.setAuthorties(auths);
		return ui;
	}

	@Override
	public Collection<User> getsUsers(Iterable<String> idz,VariableType vt)
			throws DataAccessException {
		String ids = Joiner.on("','").join(idz);
		if(vt==VariableType.department)
			return mapper.findAllByDepartments(ids);
		if(vt==VariableType.role)
			return mapper.findAllByRoles(ids);
		
		return null;
	}
	
	@Override
	public Collection<User> getsUsers(String idz, char secapchar,
			VariableType vt) throws DataAccessException {
		List<String> list = Splitter.on(secapchar).splitToList(idz);
		return getsUsers(list,vt);
	}	
	

	@Override
	public void removeAuthority(String user,  String authority) {
		mapper.rideAuthority(user, authority);
		
	}
	
	
	
	@Override
	public void removeDepartment(String user) {
		mapper.rideDepartment(user);
		
	}

	@Override
	public void removeRole(String user) {
		mapper.rideRole(user);
		
		
	}

	@Override
	public Collection<User> sameDepartment() throws DataAccessException {
		User user = null;
		//TODO 获取当前登陆用户
		Collection<User> list = mapper.findAllByDepartment(user.getDepartment().getId());
		return list;
	}

	
	@Override
	public Collection<User> findByDepartment(String id) {
		
		return mapper.findAllByDepartment(id);
	}

}
